﻿Option Compare Text
Imports System
Imports System.IO
#Const DEBUG_MODE = 0

Public Class Main
    Enum Command_Type
        Replace_Line_Length = 1
        Replace_Between = 2
        Replace_Simple = 3
        Delete_File_Match_Name = 4
        Delete_Image_Match_Partial_Image = 5
        Delete_On_Contains = 6
        Replace_Line_On_Contains = 7
    End Enum
    Structure Command
        Dim Type As Command_Type
        Dim Param1 As String
        Dim Param2 As String
        Dim Param3 As String
    End Structure

    Dim Files As List(Of String)
    Dim Dir As Directory
    Dim cIO As New uIO
    Dim Script As Command()
    Dim Script_Line As Command()
    Dim Script_Data As Command()
    Dim Script_File As Command()
    Public Kill_List As String()
    Dim utmr As Long
    Dim SysTime As Long

    Const SEP As String = "|-DD-|"


    Private Sub btnLoadDir_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLoadDir.Click
        'COMPLETE
        odd.ShowDialog()
        txtDir.Text = odd.SelectedPath
        SaveSetting(Application.ProductName, Application.ProductVersion, "Clean_Dir", txtDir.Text)
    End Sub
    Private Sub btnTreat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTreat.Click
        'COMPLETE
        Dim i As Long, Pattern As String = "*.*", msg As String, ws As StreamWriter, flst As List(Of String), rs As StreamReader
        If chkDelay.Checked Then ticker.Enabled = True
        tmr.Enabled = True
        Status("Treatment Started At " & TimeOfDay)
        pbm.Style = ProgressBarStyle.Continuous
        flst = New List(Of String)
        If FileIO.FileSystem.DirectoryExists(txtDir.Text) Then
            ' Files = Nothing
            Files = New List(Of String)
            Files.Clear()
            If chkSaveCache.Checked And txtCache.Text = "" Then
                sfd.Filter = "Directory Doctor Caches|*.ddc"
                sfd.ShowDialog()
            End If
            If (Not txtCache.Text = "") And My.Computer.FileSystem.FileExists(txtCache.Text) Then

                rs = New StreamReader(txtCache.Text)
                Do Until rs.EndOfStream
                    Files.Add(rs.ReadLine)
                Loop
                rs.Close()

            Else

                pbs.Style = ProgressBarStyle.Continuous
                Status("Caching Files...")

                Files = uIO.GetFilesRecursive(txtDir.Text, lstFileFilters.Items.Item(0))
                For i = 1 To lstFileFilters.Items.Count - 1
                    pbs.Value = Fix(i / (lstFileFilters.Items.Count) * 100)
                    Files.AddRange(uIO.GetFilesRecursive(txtDir.Text, lstFileFilters.Items.Item(i)))
                Next i

            End If

            If chkSaveCache.Checked And txtCache.Text = "" Then
                Status("Saving Cache (OPT CACHE:ON)")
                ws = New StreamWriter(sfd.FileName)
                For i = 0 To Files.Count - 1
                    ws.WriteLine(Files.Item(i))
                Next
                ws.Close()
                Status("Completed Saving Cache.")
            End If

            Status("Loaded " & Files.Count & " Files. (Successfully)")
            If chkShowLoadedFiles.Checked Then
                For i = 0 To Files.Count - 1
                    Status("Cached " & Files(i) & "...")
                Next i
            End If
            'Add File not found exception handling here.

            For i = 0 To Files.Count - 1
                Try
                    If chkFileSize.Checked = False Or (FileLen(Files(i)) < (txtFileSize.Text * 1000) And chkFileSize.Checked) Then
                        If chkSkipBacked.Checked Then
                            If Not Mid(Files(i), Len(Files(i)) - (Len(txtBackupExt.Text)) + 1) = txtBackupExt.Text Then
                                Treat_File(Files(i))
                            End If
                        Else
                            Treat_File(Files(i))
                        End If


                        pbm.Value = Fix(i / Files.Count * 100)
                        Application.DoEvents()

                    End If
                Catch ds As FileNotFoundException
                    ws = New StreamWriter(Application.StartupPath & "\notfound.log", True)
                    ws.Write(Files.Item(i))
                    ws.Close()
                    flst.Add(Files.Item(i))
                End Try
            Next



        Else
            Status("Treatment Failed...Directory does not exist (" & txtDir.Text & ")")
        End If
        If IsArray(Kill_List) Then
            msg = "Are you SURE you want to DELETE the following files filtered by the script?" & vbCrLf
            For i = 0 To UBound(Kill_List)
                msg = msg & Kill_List(i) & vbCrLf
            Next
            Try
                imgStatus.Image.Dispose()
                imgStatus2.Image.Dispose()
            Catch ex As NullReferenceException
            End Try
            frmDeleteDialog.Show(Me)

            'If MsgBox(msg, MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
            '    Kill_All_Files()
            'End If
        End If
        For i = 0 To flst.Count - 1
            lstStatus.Items.Add(flst.Item(i))
        Next
        pbm.Style = ProgressBarStyle.Marquee
        Status("Done. Idle @ " & TimeOfDay)
        tmr.Enabled = False
        ticker.Enabled = False
    End Sub
    Sub Treat_File(ByVal File As String)
        'COMPLETE
        ' Load_Script()

        Status("-----------------------------------------------------------")
        Status("Treating File (" & File & ")")
        Dim rs As StreamReader, sw As StreamWriter
        Dim data As String = "", cLine As String = ""
        If IsArray(Script) Then
            If Not Execute_External_Script(File) Then
                Try
                    rs = New IO.StreamReader(File)

                    data = rs.ReadToEnd
                    data = Execute_Internal_Script(data, True, File)
                    data = Execute_Internal_Script(data, False, File)



                    rs.Close()
                Catch ds As UnauthorizedAccessException

                    Status("Unable to access " & File)
                    Status("  -Fille Access Problem.")
                End Try
                Try


                    If chkBackup.Checked And Not My.Computer.FileSystem.FileExists(File & txtBackupExt.Text) Then
                        FileCopy(File, File & txtBackupExt.Text)
                    End If



                    sw = New IO.StreamWriter(File)
#If DEBUG_MODE = 0 Then
                    sw.Write(data)
#End If
                    sw.Close()

                Catch ex As UnauthorizedAccessException
                    Status("Acccess died to file: " & File & "(" & ex.Message & ")")

                Catch ds As IOException
                    Status("Input\Output Error to file: " & File & "(" & ds.Message & ")")
                End Try
            End If

            Status("File Treated Successfully.")
      
        Else
            Status("File Not Treated No Treatment Specified (No script to run!)")
        End If
        If chkDelay.Checked Then
            SysTime = 0
            Do While txtDelay.Text > SysTime And ticker.Enabled
                Application.DoEvents()
            Loop
        End If
    End Sub
    Sub Load_Script()
        'COMPLETE
        Dim i As Long, ind As Long
        Script_Line = Nothing
        Script_Data = Nothing
        Script_File = Nothing
        ind = 0
        If IsArray(Script) Then
            For i = 0 To UBound(Script)
                If Script(i).Type = Command_Type.Replace_Line_Length Or Script(i).Type = Command_Type.Replace_Line_On_Contains Then
                    If Not IsArray(Script_Line) Then
                        ind = -1
                    Else
                        ind = UBound(Script_Line)
                    End If
                    ReDim Preserve Script_Line(ind + 1)
                    Script_Line(UBound(Script_Line)) = Script(i)
                End If
            Next
            ind = 0
            For i = 0 To UBound(Script)
                If Script(i).Type = Command_Type.Replace_Between Or Script(i).Type = Command_Type.Replace_Simple Then
                    If Not IsArray(Script_Data) Then
                        ind = -1
                    Else
                        ind = UBound(Script_Data)
                    End If
                    ReDim Preserve Script_Data(ind + 1)
                    Script_Data(UBound(Script_Data)) = Script(i)
                End If
            Next
            ind = 0
            For i = 0 To UBound(Script)
                If Script(i).Type = Command_Type.Delete_File_Match_Name Or Script(i).Type = Command_Type.Delete_Image_Match_Partial_Image Or Script(i).Type = Command_Type.Delete_On_Contains Then
                    If Not IsArray(Script_File) Then
                        ind = -1
                    Else
                        ind = UBound(Script_File)
                    End If
                    ReDim Preserve Script_File(ind + 1)
                    Script_File(UBound(Script_File)) = Script(i)
                End If
            Next
        End If
    End Sub
    Function Execute_External_Script(ByVal File As String) As Boolean
        'COMPLETE
        Dim i As Long, ts As StreamReader, data As String
        Execute_External_Script = False
        If IsArray(Script_File) Then
            For i = 0 To UBound(Script_File)
                Select Case Script_File(i).Type
                    Case Command_Type.Delete_File_Match_Name
                        If My.Computer.FileSystem.GetName(File) = My.Computer.FileSystem.GetName(Script_File(i).Param1) Then
                            If chkRenameDelete.Checked Then
                                Rename(File, File & "_delete_")
                                Status("->DELETED " & File & ". [Not actually deleted Rename option is on. _delete_ appended to filename]")
                                Log_Changes(File, "Deleted File (Rename option ON)")
                            Else
#If DEBUG_MODE = 0 Then
                                Add_Delete_File(File)
#End If
                                Status("DELETED " & File & ".")
                                Log_Changes(File, "Deleted File (Rename option ON)")
                            End If
                            Execute_External_Script = True
                        End If
                    Case Command_Type.Delete_Image_Match_Partial_Image
                        If Image_Match(Script_File(i).Param1, File, Script_File(i).Param2) Then
                            If chkRenameDeleteImage.Checked Then
#If DEBUG_MODE = 0 Then
                                Rename(File, File & "_delete_")
#End If
                                Status("->DELETED (IMAGE) " & File & ". [Not actually deleted Rename option is on. _delete_ appended to filename]")
                                Log_Changes(File, "Deleted File (Image) (Rename option ON)")
                            Else
#If DEBUG_MODE = 0 Then
                                Add_Delete_File(File)
#End If

                                Status("->DELETED(IMAGE) " & File & ".")
                                Log_Changes(File, "Deleted File (Image)")
                            End If
                            Execute_External_Script = True
                        End If
                    Case Command_Type.Delete_On_Contains

                        Try
                            ts = New StreamReader(File)
                            data = ts.ReadToEnd
                            If Contains_All(data, Script_File(i).Param1) Then
                                If chkRenameDelete.Checked Then
#If DEBUG_MODE = 0 Then
                                    Rename(File, File & "_delete_")
#End If
                                    Status("->DELETED " & File & ". [Not actually deleted Rename option is on. _delete_ appended to filename]")
                                    Log_Changes(File, "Deleted File (Rename option ON)")
                                Else
#If DEBUG_MODE = 0 Then
                                    Add_Delete_File(File)
#End If
                                    Status("->DELETED " & File & ".")
                                    Log_Changes(File, "Deleted File")
                                End If
                            End If
                            ts.Close()
                        Catch ds As UnauthorizedAccessException

                        End Try

                End Select
            Next
        End If
    End Function

    Sub Add_Delete_File(ByVal File As String)
        If IsArray(Kill_List) Then
            ReDim Preserve Kill_List(UBound(Kill_List) + 1)
        Else
            ReDim Kill_List(0)
        End If
        Kill_List(UBound(Kill_List)) = File
    End Sub
    Sub Kill_All_Files()
        Dim i As Long
        For i = 0 To UBound(Kill_List)
            Kill(Kill_List(i))
        Next
    End Sub

    Function Partial_Match(ByVal Data As String, ByVal Match As String) As Boolean
        'COMPLETE
        If Mid(Data, 1, Len(Match)) = Match Then Return True
    End Function
    Function Contains_All(ByVal Data As String, ByVal Terms As String) As Boolean
        Dim tmp As String(), i As Long, flag As Boolean
        tmp = Split(Terms, ",")
        flag = True
        For i = 0 To UBound(tmp)
            If Not InStr(Data, tmp(i)) > 0 Then flag = False
        Next
        Return flag
    End Function
    Function Execute_Internal_Script(ByVal Data As String, ByVal Line As Boolean, Optional ByVal File As String = "") As String
        'COMPLETE
        Dim i As Long, j As Long, Lined_Data As String()
        If Line And IsArray(Script_Line) Then

            ' Lined_Data = Split(Data, vbCrLf, , CompareMethod.Text)
            Lined_Data = Split(Data, vbLf)

            For i = 0 To UBound(Script_Line)
                For j = 0 To UBound(Lined_Data)
                    Select Case Script_Line(i).Type
                        Case Command_Type.Replace_Line_Length
                            If Len(Lined_Data(j)) > Script_Line(i).Param1 And Partial_Match(Lined_Data(j), Script_Line(i).Param2) Then
                                Log_Changes(File, Script_Line(i).Param3, Lined_Data(j))
                                Lined_Data(j) = Script_Line(i).Param3
                            End If
                        Case Command_Type.Replace_Line_On_Contains
                            If Contains_All(Lined_Data(j), Script_Line(i).Param1) Then
                                Log_Changes(File, Script_Line(i).Param2, Lined_Data(j))
                                Lined_Data(j) = Script_Line(i).Param2
                            End If
                    End Select

                Next
            Next

            Data = ""
            For i = 0 To UBound(Lined_Data)
                Data = Data & Lined_Data(i) & vbLf
            Next

        Else
            If IsArray(Script_Data) Then
                For i = 0 To UBound(Script_Data)

                    Select Case Script_Data(i).Type
                        Case Command_Type.Replace_Simple
                            Log_Changes(File, "All Instances of " & Script_Data(i).Param1 & " Replaced with " & Script_Data(i).Param2)
                            Data = Replace(Data, Script_Data(i).Param1, Script_Data(i).Param2)
                            Status("Simple Replacement Scan...")
                        Case Command_Type.Replace_Between
                            Data = Replace_Between(Data, Script_Data(i).Param1, Script_Data(i).Param2, Script(i).Param3)

                    End Select
                Next
            End If

        End If
        Return Data
    End Function
    Function Replace_Between(ByVal Data As String, ByVal FirstTerm As String, ByVal LastTerm As String, ByVal ReplaceWith As String, Optional ByVal File As String = "", Optional ByVal Adaptive As Boolean = True)
        'COMPLETE
        Dim sIndex As Long, eIndex As Long, nData As String = "", Flag As Boolean
        Flag = True
        Do Until Not Flag
            Flag = False
            sIndex = InStr(Data, FirstTerm)
            If sIndex > 0 Then
                eIndex = sIndex + Len(FirstTerm) + InStr(Mid(Data, sIndex + Len(FirstTerm)), LastTerm)
                If eIndex > sIndex Then
                    Inf("Replace Between:" & FirstTerm & ", " & LastTerm)
                    Log_Changes(File, ReplaceWith, Mid(Data, sIndex, eIndex + Len(LastTerm) - 1))
                    nData = Mid(Data, 1, sIndex - 1) & ReplaceWith & Mid(Data, eIndex + Len(LastTerm) - 1)
                    Flag = True
                End If
                Data = nData
            End If
        Loop
        Return Data
    End Function
    Private Sub btnRemove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRemove.Click
        'COMPLETE
        If Not lstFileFilters.SelectedIndex = -1 Then
            lstFileFilters.Items.RemoveAt(lstFileFilters.SelectedIndex)
        End If
    End Sub
    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        'COMPLETE
        lstFileFilters.Items.Add(txtFileType.Text)
    End Sub
    Sub Status(ByVal Notification As String)
        'COMPLETE
        lstStatus.Items.Add(lstStatus.Items.Count & ": " & Notification)
        If chkAutoScroll.Checked Then
            lstStatus.SelectedIndex = (lstStatus.Items.Count - 1)
        End If
        lblStatus.Text = "Status: " & Notification & "..."
    End Sub
    Sub Inf(ByVal Msg As String)
        lstInfections.Items.Add(Msg)
    End Sub
    Function Image_Match(ByVal Image1 As String, ByVal Image2 As String, ByVal Tolerance As Single, Optional ByVal Show As Boolean = True) As Boolean
        Dim I1 As Image, I2 As Image, X As Long, Y As Long, B1 As Bitmap, B2 As Bitmap, Difference_Count As Long, Total_Pixels As Long
        'COMPLETE
        Try
            I1 = Image.FromFile(Image1)
            I2 = Image.FromFile(Image2)
            B1 = New Bitmap(I1)
            B2 = New Bitmap(I2)


            imgStatus.Image = I1
            imgStatus2.Image = I2
            imgStatus.Refresh()
            imgStatus2.Refresh()

            imgStatus.SizeMode = PictureBoxSizeMode.StretchImage

            Total_Pixels = B1.Width * B1.Height
            For X = 0 To B1.Width - 1
                For Y = 0 To B1.Height - 1
                    Try
                        If Not B1.GetPixel(X, Y) = B2.GetPixel(X, Y) Then


                            Difference_Count = Difference_Count + 1
                            'If Show Then
                            '   B1.SetPixel(X, Y, Color.White)
                            '   imgStatus.Image = Image.FromHbitmap(B1.GetHbitmap)
                            '    imgStatus.Refresh()
                            ' End If


                        End If
                    Catch ds As ArgumentException
                        Exit For
                    End Try
                    'Y = Y + 4
                Next
                Application.DoEvents()
                pbs.Value = Fix(X / B1.Width * 100)
                'X = X + 4
            Next
            imgStatus.Image = Image.FromHbitmap(B1.GetHbitmap)
            imgStatus.Refresh()

            Status("Image Analyzation Complete.")
            Status("Base Image: " & Image1)
            Status("Image: " & Image2)
            Status("Image Difference: " & (Difference_Count / (Total_Pixels)))
            If (Total_Pixels - Difference_Count) >= ((Total_Pixels) * (Tolerance)) Then
                Status("Image is a " & (100 - Fix(((Difference_Count / (Total_Pixels)) * 100))) & "% match.")
                Status("Image Passed With Tolerance of " & Tolerance & ".")
                Return True
            Else
                Status("Image Failed With Tolerance Of " & Tolerance & ".")
            End If
            Status("Image is a " & (100 - Fix(((Difference_Count / (Total_Pixels)) * 100))) & "% match.")
        Catch ds As OutOfMemoryException

        End Try
    End Function
    Private Sub btnParam1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnParam1.Click
        'COMPLETE
        On Error Resume Next
        ofd.Filter = "All Files|*.*"
        ofd.ShowDialog()
        txtParam1.Text = ofd.FileName

        If cmbCommand.SelectedIndex = 4 Then imgScript.Image = Image.FromFile(ofd.FileName)

    End Sub
    Private Sub btnParam2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnParam2.Click
        'COMPLETE
        ofd.Filter = "All Files|*.*"
        ofd.ShowDialog()
        txtParam2.Text = ofd.FileName
    End Sub
    Private Sub btnParam3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnParam3.Click
        'COMPLETE
        ofd.Filter = "All Files|*.*"
        ofd.ShowDialog()
        txtParam3.Text = ofd.FileName
    End Sub
    Private Sub btnLoadScript_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLoadScript.Click
        'COMPLETE
        Dim ts As StreamReader, tmp() As String, ind As Long
        ofd.Filter = "All Directory Doctor|*.dds"
        ofd.ShowDialog()
        SaveSetting(Application.ProductName, Application.ProductVersion, "Last_Script", ofd.FileName)
        lstFileFilters.Items.Clear()
        Script = Nothing

        ts = New IO.StreamReader(ofd.FileName)
        Do Until ts.EndOfStream
            tmp = Split(ts.ReadLine, "|-DD-|")
            If tmp(0) = "S" Then
                If IsArray(Script) Then
                    ind = UBound(Script)
                Else
                    ind = -1
                End If
                ReDim Preserve Script(ind + 1)
                Script(UBound(Script)).Type = tmp(1)
                Script(UBound(Script)).Param1 = tmp(2)
                Script(UBound(Script)).Param2 = tmp(3)
                Script(UBound(Script)).Param3 = tmp(4)

                Script(UBound(Script)).Param1 = Split_MultiLine(Script(UBound(Script)).Param1)
                Script(UBound(Script)).Param2 = Split_MultiLine(Script(UBound(Script)).Param2)
                Script(UBound(Script)).Param3 = Split_MultiLine(Script(UBound(Script)).Param3)
            End If
            If tmp(0) = "F" Then
                lstFileFilters.Items.Add(tmp(1))
            End If
            tmp = Nothing
        Loop

        Load_Script()
        UpdateScriptDisplay()
        ts.Close()
    End Sub
    Private Sub btnSaveScript_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSaveScript.Click
        'COMPLETE
        Dim ts As StreamWriter, i As Long
        sfd.Filter = "All Directory Doctor|*.dds"
        sfd.ShowDialog()
        If Not sfd.FileName = "" Then
            ts = New IO.StreamWriter(sfd.FileName)
            Script(i).Param1 = Join_MultiLine(Script(i).Param1)
            Script(i).Param2 = Join_MultiLine(Script(i).Param2)
            Script(i).Param3 = Join_MultiLine(Script(i).Param3)

            For i = 0 To UBound(Script)
                ts.WriteLine("S" & SEP & Script(i).Type & SEP & Script(i).Param1 & SEP & Script(i).Param2 & SEP & Script(i).Param3)
            Next
            For i = 0 To lstFileFilters.Items.Count - 1
                ts.WriteLine("F" & SEP & lstFileFilters.Items.Item(i))
            Next
            ts.Close()
        End If
    End Sub
    Function Join_MultiLine(ByVal Data As String) As String
        Return Replace(Replace(Data, vbCr, "|--CR--|"), vbLf, "|--LF--|")
    End Function
    Function Split_MultiLine(ByVal Data As String)
        Return Replace(Replace(Data, "|--CR--|", vbCr), "|--LF--|", vbLf)
    End Function
    Private Sub btnAddCommand_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddCommand.Click
        'COMPLETE
        Dim cmd As Command_Type, Eval As Command, ind As Long
        'Replace by Line Length X and Partial Match Y
        'Replace Between X and Y
        'Simple Replace By String X
        'Delete File by Matching FileName X
        'Delete Image by Image Recognition Comparing to Filename X and similiarity Y

        Select Case cmbCommand.SelectedIndex
            Case 0
                cmd = Command_Type.Replace_Line_Length
            Case 1
                cmd = Command_Type.Replace_Between
            Case 2
                cmd = Command_Type.Replace_Simple
            Case 3
                cmd = Command_Type.Delete_File_Match_Name
            Case 4
                cmd = Command_Type.Delete_Image_Match_Partial_Image
            Case 5
                cmd = Command_Type.Delete_On_Contains
            Case 6
                cmd = Command_Type.Replace_Line_On_Contains
        End Select
        Eval.Type = cmd
        Eval.Param1 = txtParam1.Text
        Eval.Param2 = txtParam2.Text
        Eval.Param3 = txtParam3.Text
        If Not IsArray(Script) Then
            ind = -1
        Else
            ind = UBound(Script)
        End If
        ReDim Preserve Script(ind + 1)
        Script(UBound(Script)) = Eval
        UpdateScriptDisplay()
        Load_Script()
    End Sub
    Sub UpdateScriptDisplay()
        Dim i As Long
        lstScript.Items.Clear()
        If IsArray(Script) Then
            For i = 0 To UBound(Script)
                lstScript.Items.Add([Enum].GetName(GetType(Command_Type), Script(i).Type) & "(" & Script(i).Param1 & "," & Script(i).Param2 & "," & Script(i).Param3 & ")")
            Next
        End If
    End Sub

    Private Sub Main_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.DoubleClick
        frmParentInterface.Show()
    End Sub

    Private Sub Main_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
#If DEBUG_MODE = 0 Then
        MsgBox("Make sure to BACKUP everything before running this program on anything. Also be aware that AntiVirus able to detect the files processed may cause exception errors if the AntiVirus catches the file being read by this program.")
#End If
        Me.Text = "Directory Doctor - Version " & Application.ProductVersion
        txtDir.Text = GetSetting(Application.ProductName, Application.ProductVersion, "Clean_Dir")

        If My.Computer.FileSystem.FileExists(GetSetting(Application.ProductName, Application.ProductVersion, "Last_Script")) Then
            Dim ts As StreamReader, tmp() As String, ind As Long

            lstFileFilters.Items.Clear()
            Script = Nothing

            ts = New IO.StreamReader(GetSetting(Application.ProductName, Application.ProductVersion, "Last_Script"))
            Do Until ts.EndOfStream
                tmp = Split(ts.ReadLine, "|-DD-|")
                If tmp(0) = "S" Then
                    If IsArray(Script) Then
                        ind = UBound(Script)
                    Else
                        ind = -1
                    End If
                    ReDim Preserve Script(ind + 1)
                    Script(UBound(Script)).Type = tmp(1)
                    Script(UBound(Script)).Param1 = tmp(2)
                    Script(UBound(Script)).Param2 = tmp(3)
                    Script(UBound(Script)).Param3 = tmp(4)

                    Script(UBound(Script)).Param1 = Split_MultiLine(Script(UBound(Script)).Param1)
                    Script(UBound(Script)).Param2 = Split_MultiLine(Script(UBound(Script)).Param2)
                    Script(UBound(Script)).Param3 = Split_MultiLine(Script(UBound(Script)).Param3)
                End If
                If tmp(0) = "F" Then
                    lstFileFilters.Items.Add(tmp(1))
                End If
                tmp = Nothing
            Loop

            Load_Script()
            UpdateScriptDisplay()
            ts.Close()
        End If
    End Sub

    Private Sub btnRemoveCommand_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRemoveCommand.Click
        Dim target As Long
        If IsArray(Script) And lstScript.Items.Count > 0 Then
            target = lstScript.SelectedIndex

            For i = target To UBound(Script) - 1
                Script(i) = Script(i + 1)
            Next i
            Script(UBound(Script)) = Nothing
            ReDim Preserve Script(UBound(Script) - 1)
        End If
        Load_Script()
        UpdateScriptDisplay()
    End Sub
    Private Sub btnClearLog_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClearLog.Click
        lstStatus.Items.Clear()
    End Sub

    Private Sub btnSaveLog_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSaveLog.Click
        Dim ts As StreamWriter, i As Long
        sfd.Filter = "Log Files|*.log"
        sfd.ShowDialog()
        If Not sfd.FileName = "" Then
            ts = New StreamWriter(sfd.FileName)
            For i = 0 To lstStatus.Items.Count - 1
                ts.WriteLine(lstStatus.Items.Item(i))
            Next
            ts.Close()
        End If
    End Sub
    Sub Log_Changes(Optional ByVal File As String = "", Optional ByVal Modification As String = "", Optional ByVal OldValue As String = "")
        Dim ts As StreamWriter
        lstFiles.Items.Add(File)
        If chkLogContent.Checked Then
            ts = New IO.StreamWriter(My.Computer.FileSystem.GetParentPath(Application.ExecutablePath) & "\ChangeLog.log", True)
            ts.WriteLine("-----------------------------------------------------")
            ts.WriteLine(TimeOfDay & ": File: " & File)
            ts.WriteLine()
            ts.WriteLine("***old_data_start***")
            ts.WriteLine(OldValue)
            ts.WriteLine("***old_data_end***")
            ts.WriteLine()
            ts.WriteLine("***modification_start****")
            ts.WriteLine(Modification)
            ts.WriteLine("***modification_end***")
            ts.WriteLine()
            ts.Close()
        End If
    End Sub

    Private Sub btnOpenLog_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpenLog.Click
        Shell("Notepad.exe " & My.Computer.FileSystem.GetParentPath((Application.ExecutablePath)) & "\ChangeLog.log")
    End Sub

    Private Sub txtDir_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtDir.TextChanged
        SaveSetting(Application.ProductName, Application.ProductVersion, "Clean_Dir", txtDir.Text)
    End Sub

    Private Sub btnNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNext.Click
        On Error Resume Next
        If Not (lstFiles.SelectedIndex - 1) >= (lstFiles.Items.Count - 1) And lstFiles.Items.Count > 0 Then
            lstFiles.SelectedIndex = lstFiles.SelectedIndex + 1
            Shell(txtEditor.Text & " " & lstFiles.SelectedItem)
        End If
    End Sub

    Private Sub btnPrevious_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrevious.Click
        On Error Resume Next
        If Not (lstFiles.SelectedIndex) <= 1 And lstFiles.Items.Count > 0 Then
            lstFiles.SelectedIndex = lstFiles.SelectedIndex - 1
            Shell(txtEditor.Text & " " & lstFiles.SelectedItem)
        End If
    End Sub

    Private Sub btnOpenEditor_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpenEditor.Click
        On Error Resume Next
        ofd.Filter = "All Files|*.*"
        ofd.ShowDialog()
        txtEditor.Text = ofd.FileName
    End Sub

    Private Sub tmr_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmr.Tick
        utmr = utmr + 1
        lblTime.Text = "Time: " & utmr & " Minutes"
    End Sub

    Private Sub lstFiles_MouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lstFiles.MouseDoubleClick
        On Error Resume Next
        Shell(txtEditor.Text & " " & lstFiles.SelectedItem)
    End Sub

 
    Private Sub btnCache_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCache.Click
        ofd.Filter = "Directory Doctor Caches|*.ddc"
        ofd.ShowDialog()
        txtCache.Text = ofd.FileName
    End Sub

    Private Sub ticker_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ticker.Tick
        SysTime = SysTime + 1
    End Sub

    Private Sub cmbCommand_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbCommand.SelectedIndexChanged
        If cmbCommand.SelectedItem = "Regular Expression..." Then frmBasicPatternExtract.Show(Me)
        cmbCommand.SelectedIndex = 0

    End Sub

    Private Sub TabControl1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TabControl1.SelectedIndexChanged

    End Sub
End Class
